<template>
  <div>
    <el-card>
    <el-form :inline="true" :model="query" class="query-form" size="small">
      <el-form-item class="query-form-item">
        <el-select v-model="query.status" placeholder="请选择状态" @change="onSubmit" clearable>
          <el-option label="全部" value></el-option>
          <el-option label="禁用" value="0"></el-option>
          <el-option label="正常" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="query-form-item">
        <el-input
          v-model="query.name"
          placeholder="请输入角色名称"
          prefix-icon="el-icon-search"
          @keyup.enter.native="onSubmit"
          clearable
        ></el-input>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-refresh" @click="onRest"></el-button>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
        <el-button type="primary" icon="el-icon-edit" @click.native="handleForm(null,null)">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="list"
      :header-cell-style="{background:'#F4F4F5',color:'#606266'}"
      border
    >
      <el-table-column label="角色 ID" prop="id" width="80" align="center"></el-table-column>
      <el-table-column label="角色名称" prop="name" align="center"></el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status | statusFilterType"
          >{{scope.row.status | statusFilterName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述" :show-overflow-tooltip="true" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.remark!=null">{{ scope.row.remark }}</span>
          <span v-else>暂无描述</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"  align="center"  width="240" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="info"
            size="mini"
            v-if="scope.row.id!=1&&scope.row.id!=2"
            @click.native="handleAuth(scope.row.id)"
          >授权</el-button>
          <el-button
            type="primary"
            size="mini"
            v-if="scope.row.id!=1&&scope.row.id!=2"
            @click.native="handleForm(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            v-if="scope.row.id!=1&&scope.row.id!=2"
            @click.native="handleDel(scope.$index, scope.row)"
            :loading="deleteLoading"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination-container"
      background
      :page-size="query.pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total,sizes,prev, pager, next, jumper"
      :current-page="this.query.currentPage"
      :page-sizes="[5,10, 20, 30, 50]"
      :total="totalNumber"
    ></el-pagination>

    <!--授权界面-->
    <el-dialog
      title="授权"
      :visible.sync="authFormVisible"
      :close-on-click-modal="false"
      width="50%"
      top="5vh"
      v-dialogDrag
    >
    <template slot="title">
            <div class="avue-crud__dialog__header">
                <span class="el-dialog__title">
                    <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
                    授权
                </span>
            </div>
    </template>
    <el-card>
      <el-tree
        style="max-height: 75vh;overflow-y: auto;"
        :data="authList"
        show-checkbox
        expand-on-click-node
        node-key="id"
        ref="tree"
        :props="defaultProps"
        :default-checked-keys="authDefaultCheckedKeys"
      ></el-tree>
      </el-card>
      <div slot="footer" class="dialog-footer" >
        <el-button @click.native="authFormVisible = !authFormVisible">取消</el-button>
        <el-button type="primary" @click.native="authSubmit()" :loading="authLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--表单-->
    <el-dialog
      :title="formMap[formName]"
      :visible.sync="formVisible"
      :before-close="hideForm"
      width="50%"
      top="5vh"
      v-dialogDrag
      :close-on-click-modal="false"
    >
    <template slot="title">
      <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
              <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
              {{formMap[formName]}}
          </span>
      </div>
    </template>
    <el-card>
      <el-form :model="formData" :rules="formRules" ref="dataForm">
        <el-form-item label="角色名称：" prop="name" label-width="140px">
          <el-input v-model="formData.name" placeholder="请输入角色名称" auto-complete="off"></el-input>
        </el-form-item>
<!--        <el-form-item label="状态：" prop="status" label-width="140px">-->
<!--          <el-radio-group v-model="formData.status">-->
<!--            <el-radio label="0">禁用</el-radio>-->
<!--            <el-radio label="1">正常</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label="描述：" label-width="140px" :rules="[ {required: true} ]">
          <el-input type="textarea" v-model="formData.remark"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hideForm">取消</el-button>
        <el-button type="primary" @click.native="formSubmit()" :loading="formLoading">提交</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
    authRoleList,
    authRoleAuthList,
    authRoleAuth,
    authRoleSave,
    authRoleDelete
} from "../../../api/auth/authRole";
const formJson = {
    id: "",
    name: "",
    status: "1",
    remark: "",
    listorder: ""
};
export default {
    data() {
        return {
            query: {
                name: "",
                status: "",
                currentPage: 1,
                pageSize: 5
            },
            list: [],
            totalNumber: 0,
            loading: true,
            authList: [],
            defaultProps: {
                children: "children",
                label: "title"
            },
            authLoading: false,
            authFormVisible: false,
            authFormData: {
                roleId: "",
                authRules: []
            },
            authDefaultCheckedKeys: [],
            index: null,
            formName: null,
            formMap: {
                add: "添加",
                edit: "编辑"
            },
            formLoading: false,
            formVisible: false,
            formData: formJson,
            formRules: {
                name: [
                    { required: true, message: "请输入名称", trigger: "blur" }
                ],
                status: [
                    { required: true, message: "请选择状态", trigger: "change" }
                ]
            },
            deleteLoading: false
        };
    },
    methods: {
        onRest() {
            this.query = {
                name: "",
                status: "",
                currentPage: 1,
                pageSize: 5
            };
            this.getList();
        },
        onSubmit() {
            this.query.currentPage = 1;
            this.getList();
        },
        handleCurrentChange(val) {
            this.query.currentPage = val;
            this.getList();
        },
        handleSizeChange(val) {
            this.query.pageSize = val;
            this.getList();
        },
        getList() {
            this.loading = true;
            authRoleList(this.query)
                .then(response => {
                    if (response.code) {
                        this.$message.error(response.message);
                    }
                    this.list = response.data.list || [];
                    this.totalNumber = response.data.totalNumber || 0;
                    setTimeout(() => {
                        this.loading = false;
                    }, 0.3 * 1000);
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                    this.totalNumber = 0;
                });
        },
        // 显示授权界面
        handleAuth(roleId) {
            this.authFormData.roleId = roleId;
            this.authFormData.authRules = [];
            this.authList = [];
            authRoleAuthList({ id: roleId })
                .then(response => {
                    if (response.code) {
                        this.authFormVisible = false;
                        this.$message({
                            message: response.message,
                            type: "error"
                        });
                        return;
                    }
                    this.authFormVisible = true;
                    this.authList = response.data.list || [];
                    console.log(response.data)
                    const checkedKeys = response.data.checkedKeys || [];
                    let tempCheckedKeys = [];
                    let id = null;
                    let node = null;
                    let getTreeNode = function(arr, id) {
                        for (let i in arr) {
                            let tempNode = arr[i];
                            if (tempNode.id === id) {
                                // 找到了，就不找了
                                node = tempNode;
                            }
                            // 如果还有子节点，再继续找
                            getTreeNode(tempNode.children, id);
                        }
                    };
                    for (let i in checkedKeys) {
                        id = checkedKeys[i];
                        getTreeNode(this.authList, id);
                        if (node && node.children.length <= 0) {
                            // 如果下面没有子节点，则加入
                            tempCheckedKeys.push(id);
                        }
                    }
                    this.authDefaultCheckedKeys = [];
                    this.authDefaultCheckedKeys = tempCheckedKeys;
                    // this.$refs.tree.setCheckedKeys(tempCheckedKeys);
                })
                .catch(() => {});
        },
        authSubmit() {
            this.authLoading = true;
            let getNodeParents = function(node) {
                let arr = [];
                let id = node.data.id || null;
                if (id) {
                    arr.push(node.data.id);
                }
                if (node.parent) {
                    arr = arr.concat(getNodeParents(node.parent));
                }
                return arr;
            };
            let checkedKeys = this.$refs.tree.getCheckedKeys();
            let arr = [];
            for (let checkedKey of checkedKeys) {
                let node = this.$refs.tree.getNode(checkedKey);
                arr = arr.concat(getNodeParents(node));
            }
            let setArr = new Set(arr);
            this.authFormData.authRules = [...setArr];
            if (!this.authFormData) {
                this.$alert("请至少选择一个权限", "提示", {
                    confirmButtonText: "确定"
                });
                return false;
            }
            authRoleAuth(this.authFormData)
                .then(response => {
                    this.authLoading = false;
                    if (response.code) {
                        this.$message.error(response.message);
                        return false;
                    }
                    this.$message.success("授权成功");
                    // 刷新表单
                    this.authFormVisible = false;
                })
                .catch(() => {
                    this.editLoading = false;
                });
        },
        // 隐藏表单
        hideForm() {
            // 更改值
            this.formVisible = !this.formVisible;
            // 清空表单
            this.$refs["dataForm"].resetFields();
            return true;
        },
        // 显示表单
        handleForm(index, row) {
            this.formVisible = true;
            this.formData = Object.assign({}, formJson);
            if (row !== null) {
                this.formData = Object.assign({}, row);
            }
            this.formData.status += ""; // 转为字符串（解决默认选中的时候字符串和数字不能比较的问题）
            this.formName = "add";
            if (index !== null) {
                this.index = index;
                this.formName = "edit";
            }
            // 清空验证信息表单
            if (this.$refs["dataForm"]) {
                this.$refs["dataForm"].clearValidate();
            }
        },
        formSubmit() {
            this.$refs["dataForm"].validate(valid => {
                if (valid) {
                    this.formLoading = true;
                    let data = Object.assign({}, this.formData);
                    authRoleSave(data, this.formName)
                        .then(response => {
                            this.formLoading = false;
                            if (response.code) {
                                this.$message.error(response.message);
                                return false;
                            }
                            this.$message.success("操作成功");
                            // 刷新表单
                            this.$refs["dataForm"].resetFields();
                            this.formVisible = false;
                            this.getList();
                        })
                        .catch(() => {
                            this.formLoading = false;
                        });
                }
            });
        },
        // 删除
        handleDel(index, row) {
            if (row.id) {
                this.$confirm("确认删除该记录吗?", "提示", {
                    type: "warning"
                })
                    .then(() => {
                        this.deleteLoading = true;
                        let para = { id: row.id };
                        authRoleDelete(para)
                            .then(response => {
                                this.deleteLoading = false;
                                if (response.code) {
                                    this.$message.error(response.message);
                                    return false;
                                }
                                this.$message.success("删除成功");
                                //返回第一页
                                this.query.currentPage = 1;
                                // 刷新数据
                                this.getList();
                            })
                            .catch(() => {
                                this.deleteLoading = false;
                            });
                    })
                    .catch(() => {});
            }
        }
    },
    filters: {
        statusFilterType(status) {
            const statusMap = {
                0: "gray",
                1: "success"
            };
            return statusMap[status];
        },
        statusFilterName(status) {
            const statusMap = {
                0: "禁用",
                1: "正常"
            };
            return statusMap[status];
        }
    },
    mounted() {},
    created() {
        // 加载表格数据
        this.getList();
    }
};
</script>

<style type="text/scss" lang="scss">
</style>
